package com.playmodule.vr.utils;

import android.hardware.Sensor;
import android.hardware.SensorEvent;
import android.hardware.SensorEventListener;

public class ShakeEventListener
  implements SensorEventListener
{
  private static final int MAX_PAUSE_BETHWEEN_DIRECTION_CHANGE = 200;
  private static final int MAX_TOTAL_DURATION_OF_SHAKE = 400;
  private static final int MIN_DIRECTION_CHANGE = 4;
  private static final int MIN_FORCE = 10;
  private float lastX = 0.0F;
  private float lastY = 0.0F;
  private float lastZ = 0.0F;
  private int mDirectionChangeCount = 0;
  private long mFirstDirectionChangeTime = 0L;
  private long mLastDirectionChangeTime;
  private OnShakeListener mShakeListener;

  private void resetShakeParameters()
  {
    this.mFirstDirectionChangeTime = 0L;
    this.mDirectionChangeCount = 0;
    this.mLastDirectionChangeTime = 0L;
    this.lastX = 0.0F;
    this.lastY = 0.0F;
    this.lastZ = 0.0F;
  }
  
  public void onAccuracyChanged(Sensor paramSensor, int paramInt) {

  }
  public void onSensorChanged(SensorEvent se) {
    float x = se.values[0x0];
    float y = se.values[0x1];
    float z = se.values[0x2];
    float totalMovement = Math.abs((((((x + y) + z) - lastX) - lastY) - lastZ));
    if(totalMovement > 10.0f) {
      long now = System.currentTimeMillis();
      if(mFirstDirectionChangeTime == 0x0) {
        mFirstDirectionChangeTime = now;
        mLastDirectionChangeTime = now;
      }
      long lastChangeWasAgo = now - mLastDirectionChangeTime;
      if(lastChangeWasAgo < 0xc8) {
        mLastDirectionChangeTime = now;
        mDirectionChangeCount = (mDirectionChangeCount + 0x1);
        lastX = x;
        lastY = y;
        lastZ = z;
        if(mDirectionChangeCount >= 0x4) {
          long totalDuration = now - mFirstDirectionChangeTime;
          if(totalDuration < 0x190) {
            mShakeListener.onShake();
            resetShakeParameters();
          }
        }
        return;
      }
      resetShakeParameters();
    }
  }
  public void setOnShakeListener(OnShakeListener paramOnShakeListener)
  {
    this.mShakeListener = paramOnShakeListener;
  }
  
  public static abstract interface OnShakeListener
  {
    public abstract void onShake();
  }
}
